package com.pmcc.core.web;

import com.pmcc.core.service.JwtAuthenticationResponse;
import com.pmcc.core.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.mobile.device.Device;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import com.pmcc.core.config.security.JwtAuthenticationRequest;
import com.pmcc.core.config.security.JwtTokenUtil;
import com.pmcc.core.config.security.JwtUser;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Controller
public class AuthenticationLogin {

    @Value("${jwt.header}")
    private String tokenHeader;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    LoginService loginService;


    //统一登录接口
    @PostMapping(value = "${jwt.route.authentication.path}")
    @ResponseBody
    public JwtAuthenticationResponse createAuthenticationToken(@RequestBody JwtAuthenticationRequest authenticationRequest, Device device) throws AuthenticationException {
        return loginService.login(authenticationRequest,device,null);
    }
    //刷新token接口
    @GetMapping(value = "${jwt.route.authentication.refresh}")
    @ResponseBody
    public ResponseEntity<?> refreshAndGetAuthenticationToken(HttpServletRequest request) {
        String token = request.getHeader(tokenHeader);
        String username = jwtTokenUtil.getUsernameFromToken(token);
        JwtUser user = (JwtUser) userDetailsService.loadUserByUsername(username);

        if (jwtTokenUtil.canTokenBeRefreshed(token, user.getLastPasswordResetDate())) {
            String refreshedToken = jwtTokenUtil.refreshToken(token);
            String auth="";
            if(user.getAuthorities().size()>0){
                auth=user.getAuthorities().toArray()[0].toString();
            }
            return ResponseEntity.ok(new JwtAuthenticationResponse(refreshedToken,"ok",auth,request.getAuthType().toString()));
        } else {
            return ResponseEntity.badRequest().body(null);
        }
    }

    /*
     * 登录页需要重新发起一次请求。需要返回index.html
    */
    @GetMapping(value = "/login")
    public String getLoginPage() {
        return "index.html";
    }



}
